#!/bin/sh

WORK_DIR="/tmp/17ce/"
SUCC_FLE=$WORK_DIR"ssss"
EXEC_FLE=$WORK_DIR"17ce_v3"
CDN_BASE="http://gitee.com/xiahuo/K2-apps/raw/master/K2_apps/17ce"

logging()
{
    logger -t "[17ce_daemon]" "$1"
}


wget_install()
{
    [ -f $1 ] && return 0
	wget --no-check-certificate -q -T 10 -O $1 $2 2>&1 > /dev/null
    if [ $? -ne 0 ]; then
        logging "download $2 failed"
        return 1
    fi
	chmod +x $1
    return $?
}


download_files()
{
    if [ ! -d $WORK_DIR ]; then
        mkdir -p $WORK_DIR
    fi
	cd $WORK_DIR
    wget_install 17ce_v3                $CDN_BASE/bin/17ce_v3
    [ $? -ne 0 ] && return 1
    wget_install conf.json              $CDN_BASE/bin/conf.json
    [ $? -ne 0 ] && return 1
    wget_install libgcc_s.so.1          $CDN_BASE/lib/libgcc_s.so.1
    [ $? -ne 0 ] && return 1
    wget_install libcurl.so.4           $CDN_BASE/lib/libcurl.so.4
    [ $? -ne 0 ] && return 1
	wget_install libstdc++.so.6         $CDN_BASE/lib/libstdc++.so.6.0.21
    [ $? -ne 0 ] && return 1
	wget_install libpolarssl.so.7       $CDN_BASE/lib/libpolarssl.so.1.3.9
    [ $? -ne 0 ] && return 1
	ln -sf $WORK_DIR/libpolarssl.so.7   libmbedtls.so.9
    [ $? -ne 0 ] && return 1
	ln -sf /lib/libc.so.0               libc.so
    [ $? -ne 0 ] && return 1
    touch ./ssss
}


check_mem()
{
    mem=`ps | grep 17ce_v3 | grep -v grep | awk '{print $3}'`
    if [ "$mem" -gt 25000 ]; then
        logging "memory out, $mem"
        killall -9 17ce_v3
        return 1
    fi
    return 0
}


daemon()
{
    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$WORK_DIR
    while [ 1 ]; do
        pid=`pidof 17ce_v3`
        if [ $? -ne 0 ]; then
            logging "17ce client has been stoped"
            logging "start 17ce client"
            $EXEC_FLE -u $1 2>&1 > /dev/null
            [ $? -eq 0 ] && logging "start \"$EXEC_FLE $1\" successful"
        #else
            #check_mem
            #[ $? -ne 0 ] && sleep 1 && continue
        fi
        sleep 5
    done
}


do_start()
{
    while [ ! -f $SUCC_FLE ]; do
        logging "check and download install files"
        download_files
        sleep 5
    done
    logging "start 17ce daemon process"
    daemon $1
}


if [ $# -ne 1 ]; then
    echo "Usage: $0 <id>"
    exit 1
fi

do_start $1
